<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- <div>
        <el-button type="primary">添加角色</el-button>
      </div> -->
      <!-- 角色列表 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row :class="['bd_bottom', index === 0 ? 'bd_top' : '']" 
            v-for="(item_1, index) in scope.row.children" 
            :key="item_1.id"
            type="flex"
            align="middle">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="tagClose(scope.row, item_1.id)">{{item_1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级、三级权限 -->
              <el-col :span="19">
                <!-- for循环嵌套渲染二级权限 -->
                <el-row :class="{'bd_top': index_2 !== 0}" 
                v-for="(item_2, index_2) in item_1.children" 
                :key="item_2.id"
                type="flex"
                align="middle">
                  <el-col :span="6">
                    <el-tag closable type="success" @close="tagClose(scope.row, item_2.id)">{{item_2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                <!-- for循环嵌套渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag closable type="warning" 
                    v-for="(item_3, index_3) in item_2.children" 
                    :key="item_3.id"
                    @close="tagClose(scope.row, item_3.id)">
                      {{item_3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" align="center"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="getEditForm(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteRole(scope.row.id)">删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-setting" @click="showRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="dialogClose">
      <el-form ref="dialogFom" :model="addRoleForm" :rules="addRoleFormRule" :status-icon="true">
        <el-form-item label="角色名称" label-width="80px" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" label-width="80px" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="dialogClose">
      <el-form ref="dialogFom" :model="editRoleForm" :rules="addRoleFormRule" :status-icon="true">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole(editRoleForm)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="添加角色权限"
      :visible.sync="rightDialogVisible"
      width="50%"
      @close="rightClose">
      <!-- 树形控件 -->
      <!-- 若不绑定node-key，则无法使用默认勾选 -->
      <el-tree :data="rightList" 
      :props="treeProp"
      show-checkbox
      node-key="id"
      ref="rightTree"
      :default-checked-keys="defKeys"
      :default-expand-all="true"></el-tree>
      <span slot="footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import { getHomeData } from 'network/home.js'

  export default {
    name: 'Roles',
    data() {
      return {
        // 角色列表数据
        roleList: [],
        // 是否打开添加角色的对话框
        addDialogVisible:false,
        // 添加角色表单
        addRoleForm: {
          roleName: '',
          roleDesc: ''
        },
        // 检验添加角色表单
        addRoleFormRule: {
          roleName: [
            { required: true, message: '角色名称不能为空', trigger: 'blur' },
            { min: 2, max: 6, message: '角色名称应当为2~6个字符', trigger: 'blur'}
          ],
          roleDesc: [
            { max: 8, message: '角色描述最多为8个字', trigger: 'blur'}
          ]
        },
        // 编辑角色的表单
        editRoleForm: {},
        // 是否打开编辑角色的对话框
        editDialogVisible: false,
        // 是否打开分配权限对话框
        rightDialogVisible: false,
        // 保存所有权限
        rightList: [],
        // 树形控件相关配置
        treeProp: {
          children: 'children',
          label: 'authName'
        },
        // 默认选中的权限,只需要三级权限的就可以了
        defKeys: [],
        roleId: ''
      }
    },
    created() {
      this.getRoleList()
    },
    methods: {
      // 清空表单
      dialogClose() {
        this.$refs.dialogFom.resetFields();
      },
      // 获取角色列表
      getRoleList() {
        getHomeData({url: 'roles'})
        .then(res => {
          this.roleList = res.data;
        })
        .catch(() => this.$message.error(new Error('获取角色列表失败')))
      },
      // 添加角色
      addRole() {
        this.$refs.dialogFom.validate(valid => {
          if(!valid) return;
          getHomeData({
            url: 'roles',
            data: this.addRoleForm
          }, 'post')
          .then(res => {
            this.$message({
              type: 'success',
              message: res.meta.msg
            })
            this.addDialogVisible = false;
            this.getRoleList();
          })
          .catch(() => this.$message.error(new Error('添加角色失败')))
        })
      },
      // 获取所编辑角色的信息
      getEditForm(id) {
        getHomeData({
          url: `roles/${id}`
        })
        .then(res => {
          this.editRoleForm = res.data;
          this.editDialogVisible = true;
        })
        .catch(() => this.$message.error(new Error('获取角色信息失败')))
      },
      // 编辑角色
      editRole(editRoleForm) {
        this.$refs.dialogFom.validate(valid => {
          if(!valid) return;
          getHomeData({
            url: `roles/${editRoleForm.roleId}`,
            data: {
              roleName: editRoleForm.roleName,
              roleDesc: editRoleForm.roleDesc
            }
          }, 'put')
          .then(res => {
            this.$message({
              type: 'success',
              message: '编辑角色信息成功'
            })
            this.editDialogVisible = false;
            this.getRoleList();
          })
          .catch(() => this.$message.error(new Error('编辑角色信息失败')))
          })
      },
      // 删除角色
      deleteRole(id) {
        this.$confirm('是否确认删除该角色？', '删除角色', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          return getHomeData({
          url: `roles/${id}`
        }, 'delete')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
          return new Promise(() => {});     
        })
        .then(res => {
          this.$message({
              type: 'success',
              message: res.meta.msg
            })
          this.getRoleList();
        })
        .catch(() => this.$message.error(new Error('删除角色失败')))
      },
      // 根据id删除权限
      tagClose(role, id) {
        this.$confirm('是否确认永久删除该权限？', '删除权限', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          return getHomeData({
            url: `roles/${role.id}/rights/${id}`
          }, 'delete')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
          return new Promise(() => {});     
        })
        .then(res => {
          this.$message({
            type: 'success',
            message: '删除角色权限成功'
          });
          // 在这里不需要重新获取数据进行整体刷新，这样体验不好
          // 这样能使其仅仅局部刷新，效果更好
          role.children = res.data;
        })
        .catch(() => this.$message.error(new Error('删除角色权限失败')))
      },
      // 获取所有权限列表
      showRightDialog(role) {
        this.roleId = role.id;
        this.getLeafKeys(role, this.defKeys);
        getHomeData({
          url: 'rights/tree'
        })
        .then(res => {
          this.rightList = res.data
        })
        .catch(() => this.$message.error(new Error('获取权限失败')))
        this.rightDialogVisible = true;
      },
      // 获取当前用户包含的权限
      getLeafKeys(node, arr) {
        if(!node.children) {
          return arr.push(node.id);
        }
        node.children.forEach(item => this.getLeafKeys(item, arr));
      },
      // 在关闭时清空权限列表
      rightClose() {
        this.defKeys = [];
      },
      // 添加权限
      allotRight() {
        const keys = [...this.$refs.rightTree.getHalfCheckedKeys(), ...this.$refs.rightTree.getCheckedKeys()];
        const idStr = keys.join(',');
        getHomeData({
          url: `roles/${this.roleId}/rights`,
          data: {
            rids: idStr
          }
        }, 'post')
        .then(res => {
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
          this.getRoleList();
          this.rightDialogVisible = false;
        })
        .catch(() => this.$message.error(new Error('修改权限失败')))
      }
    },
  }
</script>

<style scoped>
  /* .el-icon-arrow-right:hover {
    cursor: pointer;
    color: #409eff;
    font-size: 18px;
    font-weight: bold;
  } */
  .el-col .el-button {
    margin-bottom: 15px;
  }
  .el-tag {
    margin: 7px;
  }
  .bd_top {
    border-top: 1px solid #eee;
  }
  .bd_bottom {
    border-bottom: 1px solid #eee;
  }
</style>